package com.penjin.android.activity.kaoqin;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinDate;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.domain.RongyuRankBean;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.BitmapUtils;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.JsonUtils;
import com.penjin.android.utils.ScreenUtils;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.PenjinAvatar;
import com.penjin.android.view.TitleBarView;
import com.penjin.android.view.penjin.RongyuRankItem;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Administrator on 2016/4/20.
 * 荣誉榜
 */
public class RongyuBangActivity extends Activity {

    TitleBarView titleBarView;
    CustomProgressDialog progressDialog;

    PenjinUser user;
    PenjinCompany company;
    PenjinStaff staff;
    PenjinDate nowDate;
    PenjinDate pickDate;

    HttpService httpService;
    TextHttpResponseHandler handler;

    boolean isFirstDataLoaded = false;

    boolean isLoadingData = false;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                refreshUI();
            } else if (msg.what == 2) {
                isLoadingData = false;
                isFirstDataLoaded = true;
                ToastHelper.showMessage("暂无数据", getApplicationContext());
            }
        }
    };

    ArrayList<RongyuRankBean> dataList = new ArrayList<>();

    GridView gridView;
    RongyuRankAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_rongyubang);
        initData(savedInstanceState);
        initView();
        initHttp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (user.isInCompany()) {
            if (!isFirstDataLoaded && !isLoadingData) {
                if (HttpUtil.isNetworkAvailable(this)) {
                    launchRequest();
                } else {
                    ToastHelper.showNoNetwork(getApplicationContext());
                }
            }
        } else {
            ToastHelper.showNotBindCompany(getApplicationContext());
        }
    }

    private void initData(Bundle bundle) {
        UserService userService = UserService.getInstance(getApplicationContext());
        user = userService.getCurrentUser();
        if (user == null) {
            finish();
            ToastHelper.showNotLogin(getApplicationContext());
        }
        if (user.isInCompany()) {
            company = userService.getCurrentCompany();
            staff = userService.getCurrentStaff();
        }
        nowDate = new PenjinDate(new Date());
        pickDate = new PenjinDate(new Date());
    }

    public void initView() {
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });

        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");

        gridView = (GridView) findViewById(R.id.gridView);
        adapter = new RongyuRankAdapter(this);
        gridView.setAdapter(adapter);
    }

    private void initHttp() {
        httpService = HttpService.getInstance(getApplicationContext());
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                isLoadingData = false;
                if (s != null) {
                    System.out.println(s);
                }
                ToastHelper.showServerError(getApplicationContext());

            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                System.out.println(s);
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    boolean result = jsonObject.getBoolean("result");
                    if (result) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        dataList.clear();
                        for (int j = 0; j < jsonArray.length(); j++) {
                            JSONObject entity = jsonArray.getJSONObject(j);
                            RongyuRankBean bean = new RongyuRankBean();
                            bean.department = entity.getString("Department");
                            bean.score = entity.getString("Score");
                            bean.name = entity.getString("Name");
                            bean.staffNumber = entity.getString("StaffNumber");
                            bean.lateMinutes = entity.getString("LateMintues");
                            bean.headUrl = entity.getString("HeadUrl");
                            bean.rank = j + 1;
                            dataList.add(bean);
                        }
                        mHandler.sendEmptyMessage(1);
                    } else {
                        mHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    isLoadingData = false;
                    isFirstDataLoaded = true;
                    ToastHelper.showMessage("返回内容出错", getApplicationContext());
                }
            }
        };
    }

    private void launchRequest() {
        isLoadingData = true;
        RequestParams requestParams = new RequestParams();
        requestParams.put("companyId", company.getCompanyId());
        requestParams.put("userName", user.getPhone());
        requestParams.put("year", pickDate.year);
        requestParams.put("month", pickDate.month);
        progressDialog.show();
        try {
            httpService.postRequest(this, HttpConstants.HOST + HttpConstants.KaoqinHonorWallCompany, requestParams, handler);
        } catch (Exception e) {
            isLoadingData = false;
            progressDialog.dismiss();
            ToastHelper.showConnectionError(getApplicationContext());
        }
    }

    private void refreshUI() {
        adapter.notifyDataSetChanged();
        isLoadingData = false;
        isFirstDataLoaded = true;
    }

    class RongyuRankAdapter extends BaseAdapter {

        Context mContext;

        public RongyuRankAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new RongyuRankItem(mContext);
                GridView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, ScreenUtils.dp2px(mContext, 180));
                convertView.setLayoutParams(layoutParams);
                convertView.setBackgroundDrawable(new BitmapDrawable(BitmapUtils.readBitMap(mContext, R.drawable.pj_rank_bg)));
            }
            RongyuRankItem item = (RongyuRankItem) convertView;
            RongyuRankBean bean = dataList.get(position);
            item.setImage(bean.headUrl);
            item.setRank(bean.rank + "");
            item.setName(bean.name + "    " + bean.department);
            item.setScore(bean.score);
            return convertView;
        }
    }

}
